package com.example.demo.controller;

import com.example.demo.commons.Utils.CodesUtils;
import com.example.demo.commons.Utils.EmailUtils;
import com.example.demo.commons.r.Codes;
import com.example.demo.commons.r.R;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import jakarta.validation.constraints.NotBlank;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/email")
@Validated
public class EmailController {
     @Autowired
     private UserService userService;
     @Autowired
     private EmailUtils emailUtils;
     @RequestMapping("/sendCode")
    public R sendCode(@NotBlank(message = "用户名不能为空") String username) {
        //根据用户获取用户的邮箱
       User user = userService.queryUserName(username);
        if (user == null) {
           return R.fail(Codes.USER_NOT_FOUND);
        }
        //用户存在
         String email = user.getEmail();
        //生成验证码
         int codes = (int) (Math.random()*90000+1000);
        //发送邮件
        emailUtils.sendEmailCode(email,codes);
        //将验证码保存到Map集合中
        CodesUtils.putCode(username,codes);
        // 返回前端的验证码隐藏部分
        String content = email.substring(3,email.lastIndexOf("@"));
        email = email.replace(content,"**********");
        return R.succ(email);
    }
}

